package com.lekang.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.lekang.dto.AddBillDto;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.domain.Bill;
import com.lekang.service.IBillService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 账单Controller
 * 
 * @author ruoyi
 * @date 2025-10-15
 */
@RestController
@RequestMapping("/financialManagement/accountEntryList")
public class BillController extends BaseController
{
    @Autowired
    private IBillService billService;

    /**
     * 查询账单列表
     */
    @PreAuthorize("@ss.hasPermi('financialManagement:accountEntryList:list')")
    @GetMapping("/list")
    public TableDataInfo list(Bill bill)
    {
        startPage();
        List<Bill> list = billService.selectBillList(bill);
        return getDataTable(list);
    }

    /**
     * 导出账单列表
     */
    @PreAuthorize("@ss.hasPermi('financialManagement:accountEntryList:export')")
    @Log(title = "账单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Bill bill)
    {
        List<Bill> list = billService.selectBillList(bill);
        ExcelUtil<Bill> util = new ExcelUtil<Bill>(Bill.class);
        util.exportExcel(response, list, "账单数据");
    }

    /**
     * 获取账单详细信息
     */
    @PreAuthorize("@ss.hasPermi('financialManagement:accountEntryList:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(billService.selectBillById(id));
    }

    /**
     * 新增账单
     */
    @PreAuthorize("@ss.hasPermi('financialManagement:accountEntryList:add')")
    @Log(title = "账单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Bill bill)
    {
        return toAjax(billService.insertBill(bill));
    }
    /**
     * 新增：一对多新增账单（主表+详情表）
     * 路径加 "/withDetails" 区分原有单条新增，避免接口冲突
     */
    @PreAuthorize("@ss.hasPermi('financialManagement:accountEntryList:add')") // 复用原有权限，无需新增
    @Log(title = "账单（含详情）", businessType = BusinessType.INSERT) // 日志标题明确含详情
    @PostMapping("/withDetails") // 新增接口路径，区分原有接口
    public AjaxResult addWithDetails(@RequestBody AddBillDto addBillDto)
    {
        try {
            // 调用Service层一对多新增方法
            boolean success = billService.addBillWithDetails(addBillDto);
            return success ? AjaxResult.success("账单及详情新增成功") : AjaxResult.error("账单及详情新增失败");
        } catch (RuntimeException e) {
            // 捕获Service层抛出的业务异常（如详情为空、总金额为负），返回具体错误信息
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            // 捕获其他系统异常，返回通用提示
            return AjaxResult.error("系统异常，请稍后重试");
        }
    }

    @PreAuthorize("@ss.hasPermi('financialManagement:accountEntryList:add')") // 复用原有权限，无需新增
    @Log(title = "账单（含详情）", businessType = BusinessType.INSERT) // 日志标题明确含详情
    @PostMapping("/addBillWithDetails") // 新增接口路径，区分原有接口
    public AjaxResult addBillWithDetails(@RequestBody AddBillDto addBillDto)
    {
        try {
            // 调用Service层一对多新增方法
            boolean success = billService.addBillWithBillDetails(addBillDto,null);
            return success ? AjaxResult.success("账单及详情新增成功") : AjaxResult.error("账单及详情新增失败");
        } catch (RuntimeException e) {
            // 捕获Service层抛出的业务异常（如详情为空、总金额为负），返回具体错误信息
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            // 捕获其他系统异常，返回通用提示
            return AjaxResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 修改账单
     */
    //@PreAuthorize("@ss.hasPermi('financialManagement:accountEntryList:edit')")
    @Log(title = "账单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Bill bill)
    {
        return toAjax(billService.updateBill(bill));
    }

    /**
     * 删除账单
     */
    @PreAuthorize("@ss.hasPermi('financialManagement:accountEntryList:remove')")
    @Log(title = "账单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(billService.deleteBillByIds(ids));
    }

    /**
     * 根据老人ID查询账单列表
     */
    @PreAuthorize("@ss.hasPermi('financialManagement:accountEntryList:list')")
    @GetMapping("/listByElderlyId/{elderlyId}")
    public TableDataInfo listByElderlyId(@PathVariable("elderlyId") Long elderlyId) {
        List<Bill> list = billService.selectBillListByElderlyId(elderlyId);
        return getDataTable(list);
    }
    /**
     * 根据ID修改账单状态
     */
    @Log(title = "账单状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody Bill bill) {
        String s = billService.updateBillStatus(bill);
        return AjaxResult.success(s);
    }
}
